package com.njupt.sellsec.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 17:29 2018/7/27
 * @Modified By:
 **/
@Service
public class RedisService {
    @Autowired
    private JedisPool jedisPool;


    public <T> T get(KeyPrefix prefix,String key,Class<T> clazz){
        Jedis jedis = null;
        try{

            jedis = jedisPool.getResource();
           // System.out.println(prefix.getPrefix()+key);
            String result = jedis.get(prefix.getPrefix()+key);
            T t = stringToBean(result,clazz);
            return t;
        }finally {
            returnToPool(jedis);
        }

    }

    public <T> boolean set(KeyPrefix prefix,String key,T value){
        Jedis jedis = null;
        try{

            jedis = jedisPool.getResource();
            String str = beanToString(value);
            if (StringUtils.isEmpty(str)){
                return false;
            }
            int expire = prefix.expireSeconds();
            if (expire<=0){
                jedis.set(prefix.getPrefix()+key,str);
            }else {

                jedis.setex(prefix.getPrefix()+key,expire,str);
            }
            return true;
        }finally {
            returnToPool(jedis);
        }

    }

    public <T> boolean exits(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix.getPrefix()+key;
            return jedis.exists(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    public <T> Long derc(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix.getPrefix()+key;
            return jedis.decr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    public <T> Long incr(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix.getPrefix()+key;
            return jedis.incr(realKey);
        }finally {
            returnToPool(jedis);

        }
    }

    public boolean del(KeyPrefix prefix,String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realKey = prefix.getPrefix()+key;
            long res = jedis.del(realKey);
            return res>0;
        }finally {
            returnToPool(jedis);
        }
    }

    public boolean delete(KeyPrefix prefix) {
        if(prefix == null) {
            return false;
        }
        List<String> keys = scanKeys(prefix.getPrefix());
        if(keys==null || keys.size() <= 0) {
            return true;
        }
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(keys.toArray(new String[0]));
            return true;
        } catch (final Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if(jedis != null) {
                jedis.close();
            }
        }
    }

    public List<String> scanKeys(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            List<String> keys = new ArrayList<String>();
            String cursor = "0";
            ScanParams sp = new ScanParams();
            sp.match("*"+key+"*");
            sp.count(100);
            do{
                ScanResult<String> ret = jedis.scan(cursor, sp);
                List<String> result = ret.getResult();
                if(result!=null && result.size() > 0){
                    keys.addAll(result);
                }
                //再处理cursor
                cursor = ret.getStringCursor();
            }while(!cursor.equals("0"));
            return keys;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }



    public static <T> String beanToString(T value) {
        Class<?> clazz = value.getClass();
        if (value==null){
            return null;

        }else if (clazz==int.class||clazz==Integer.class){
            return ""+value;
        }else if (clazz==String.class){
            return (String) value;
        }else if (clazz==long.class||clazz==Long.class){
            return ""+value;
        }else {
            return JSON.toJSONString(value);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T stringToBean(String str,Class<T> clazz) {

        if (str==null||str.length()<=0||clazz==null){
            return null;

        }else if (clazz==int.class||clazz==Integer.class){
            return (T) Integer.valueOf(str);
        }else if (clazz==String.class){
            return (T) String.valueOf(str);
        }else if (clazz==long.class||clazz==Long.class){
            return (T) Long.valueOf(str);
        }else {
            return JSON.toJavaObject(JSON.parseObject(str),clazz);
        }
    }

    private void returnToPool(Jedis jedis) {
        if (jedis!=null){
            jedis.close();
        }
    }


}
